package com.rjj.wlqq.wx.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.rjj.wlqq.wx.common.constant.HttpUrl;
import com.rjj.wlqq.wx.entity.template.Content;
import com.rjj.wlqq.wx.entity.template.Template;
import com.rjj.wlqq.wx.entity.template.WxTemplateResponse;
import com.rjj.wlqq.wx.entity.template.ticket.Ticket;
import com.rjj.wlqq.wx.service.WxService;
import com.rjj.wlqq.wx.tool.WxKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author r
 * @date 2020/12/27 13:40
 */
@Service
public class WxServiceImpl implements WxService
{
    @Autowired
    private WxKit wxKit;

    @Override
    public Ticket getTicketResponse(String json)
    {
        System.out.println(json);
        final String body = HttpRequest.post(HttpUrl.getTicketUrl(wxKit.getAccessToken()))
                .contentType("application/json; encoding=utf-8")
                .body(json)
                .execute()
                .body();
        if (body.contains("errcode") && body.contains("errmsg"))
        {
            System.out.println("ticket===" + body);
        }
        return JSON.parseObject(body, Ticket.class);
    }


    @Override
    public WxTemplateResponse sendTemplateMessage(String toUser, String message1, String message2, String url)
    {
        final Template template = Template.Builder()
                .setTemplate_id("iDXAYYD3sTDpf2zBMw57VqvtK_wrE_ODLz0x2jYU4lY")
                .setTouser(toUser)
                .setUrl(url)
                .setData("first", Content.Builder().setValue(message1).setColor("#173177").build())
                .setData("keywork", Content.Builder().setValue(message2).setColor("#173177").build());

        final String body = HttpRequest.post(HttpUrl.getTemplateUrl(wxKit.getAccessToken()))
                .body(JSON.toJSONString(template))
                .execute()
                .body();
        return JSON.parseObject(body, WxTemplateResponse.class);
    }

    @Override
    public WxTemplateResponse sendTemplateMessage(Template template)
    {
        final String body = HttpRequest.post(HttpUrl.getTemplateUrl(wxKit.getAccessToken()))
                .body(JSON.toJSONString(template))
                .execute()
                .body();
        return JSON.parseObject(body, WxTemplateResponse.class);
    }
}
